using UnityEngine;
using Unity.Collections;
using Unity.Jobs;

public class SpiderJobMove : MonoBehaviour
{
    private Camera _camera;
    private Vector2 _targetDirection;
    private float _changeDirectionCooldown;
    private float _speed;
    private float _rotationSpeed;

    private NativeArray<float> _changeDirectionCooldownResult;
    private NativeArray<Vector2> _targetDirectionResult;
    private NativeArray<Vector2> _positionResult;
    private NativeArray<Quaternion> _rotationResult;

    private JobHandle _jobHandle;

    private void Awake()
    {
        _camera = Camera.main;
        _targetDirection = Vector2.up;
        _speed = Random.Range(2f, 5f);
        _rotationSpeed = Random.Range(90f, 180f);

        _changeDirectionCooldownResult = new NativeArray<float>(1, Allocator.Persistent);
        _targetDirectionResult = new NativeArray<Vector2>(1, Allocator.Persistent);
        _positionResult = new NativeArray<Vector2>(1, Allocator.Persistent);
        _rotationResult = new NativeArray<Quaternion>(1, Allocator.Persistent);
    }

    private void Update()
    {
        Vector2 screenPoint = _camera.WorldToScreenPoint(transform.position);

        SpiderJob job = new SpiderJob(
            _targetDirection,
            _changeDirectionCooldown,
            _speed,
            _rotationSpeed,
            Time.deltaTime,
            (uint)Random.Range(1, 1000),
            screenPoint,
            _camera.pixelWidth,
            _camera.pixelHeight,
            transform.rotation,
            transform.position,
            _changeDirectionCooldownResult,
            _targetDirectionResult,
            _positionResult,
            _rotationResult);

        _jobHandle = job.Schedule();
    }

    private void LateUpdate()
    {
        _jobHandle.Complete();

        _targetDirection = _targetDirectionResult[0];
        _changeDirectionCooldown = _changeDirectionCooldownResult[0];
        transform.rotation = _rotationResult[0];
        transform.position = _positionResult[0];
    }

    private void OnDestroy()
    {
        _targetDirectionResult.Dispose();
        _changeDirectionCooldownResult.Dispose();
        _positionResult.Dispose();
        _rotationResult.Dispose();
    }
}